/**
 * 将输入文本转换为固定长度的哈希字符串
 * @param text 需要哈希化的文本
 * @param length 返回哈希值的长度（默认为 10）
 * @returns 哈希后的字符串
 */
export function hashText(text: string, length: number = 10): string {
    let hash = 0;
    
    // 基础哈希计算
    for (let i = 0; i < text.length; i++) {
      const char = text.charCodeAt(i);
      hash = ((hash << 5) - hash) + char;
      hash = hash & hash; // 转换为32位整数
    }
  
    // 确保hash为正数
    hash = Math.abs(hash);
    
    // 生成字符集
    const characters = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
    let result = '';
    
    // 转换为指定长度的字符串
    while (result.length < length) {
      const index = hash % characters.length;
      result += characters[index];
      hash = Math.floor(hash / characters.length);
      
      // 如果hash被用完，但结果还未达到指定长度，重新生成hash
      if (hash === 0 && result.length < length) {
        hash = result.split('').reduce((acc, char) => {
          return ((acc << 5) - acc) + char.charCodeAt(0);
        }, 0);
        hash = Math.abs(hash);
      }
    }
    
    return result;
}
  

/**
 * 返回一个随机id
 * @returns 随机id
 */
export function uuid() {
  let reg = /[xy]/g;
  let templete = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx-xxxx';
  let d = new Date().getTime();
  const uuid = templete.replace(reg, function (c) {
    var r = (d + Math.random() * 16) % 16 | 0;
    d = Math.floor(d / 16);
    return (c === 'x' ? r : (r & 0x3 | 0x8)).toString(16);
  });
  return uuid;
}